package rolevalidator

import (
	"fmt"
	"time"
	"yunj/pkg/global"
	"yunj/pkg/yunj/app/enum/stateenum"
	"yunj/pkg/yunj/app/model"
	"yunj/pkg/yunj/util"

	"github.com/worklz/go-validate"
)

type Role struct {
	validate.Validator
}

func (v *Role) HandleDatas(datas map[string]interface{}, scene string) (err error) {
	if scene == "FormSubmit" {
		err = v.HandleDatasByFormSubmit(datas)
		if err != nil {
			return
		}
	}
	return
}

func (v *Role) HandleDatasByFormSubmit(datas map[string]interface{}) (err error) {
	datas = util.MapFloat64ToUints(datas)
	currTime := time.Now().In(time.Local)
	dbRole := &model.AdminRole{
		Name:      util.MapKeyValue(datas, "name", ""),
		Intro:     util.MapKeyValue(datas, "intro", ""),
		UpdatedAt: &currTime,
	}
	// id
	var id uint64
	if idRaw, exists := datas["id"]; exists {
		var idVal uint64
		if idVal, err = util.ToUint64(idRaw); err == nil && idVal > 0 {
			if idVal == 1 {
				err = fmt.Errorf("系统内置初始超管角色不允许修改！")
				return
			}
			id = idVal
		}
	}
	// code
	code := util.MapKeyValue(datas, "code", "")
	if code != "" {
		// 判断是否存在
		codeExistsQuery := global.MySQL.Model(&model.AdminRole{}).Where("`code` = ?", code)
		if id > 0 {
			codeExistsQuery.Where("`id` != ?", id)
		}
		var codeExistsCount int64
		if err = codeExistsQuery.Count(&codeExistsCount).Error; err != nil {
			return fmt.Errorf("数据查询异常！%v", err)
		}
		if codeExistsCount > 0 {
			return fmt.Errorf("岗位标识【%s】已存在！", code)
		}
		dbRole.Code = code
	}
	// auths
	auths := model.StrSliceJson{}
	if topAuthsRaw, exists := datas["top_auths"]; exists {
		if topAuths, ok := topAuthsRaw.([]any); ok {
			for _, topAuth := range topAuths {
				if topAuthStr, ok := topAuth.(string); ok {
					auths = append(auths, topAuthStr)
				}
			}
		}
	}
	if sidebarAuthsRaw, exists := datas["sidebar_auths"]; exists {
		if sidebarAuths, ok := sidebarAuthsRaw.([]any); ok {
			for _, sidebarAuth := range sidebarAuths {
				if sidebarAuthStr, ok := sidebarAuth.(string); ok {
					auths = append(auths, sidebarAuthStr)
				}
			}
		}
	}
	if otherAuthsRaw, exists := datas["other_auths"]; exists {
		if otherAuths, ok := otherAuthsRaw.([]any); ok {
			for _, otherAuth := range otherAuths {
				if otherAuthStr, ok := otherAuth.(string); ok {
					auths = append(auths, otherAuthStr)
				}
			}
		}
	}
	dbRole.Auths = auths
	if id > 0 {
		// 编辑
		dbRole.Id = id
	} else {
		// 新增
		dbRole.CreatedAt = &currTime
		dbRole.State = stateenum.NORMAL
	}
	datas["dbRole"] = dbRole
	return
}
